package com.cn.struts2;

import cn.com.allunion.common.UUIDGenerator;
import cn.com.allunion.common.page.PageView;
import cn.com.allunion.common.page.QueryResult;
import cn.com.allunion.sms.pojo.Smsbusiness;
import cn.com.allunion.sms.pojo.Userbase;
import cn.com.allunion.sms.pojo.UserbaseAuthority;
import cn.com.allunion.sms.pojo.UserbaseSmsbusiness;
import cn.com.allunion.sms.service.mybatis.AuthorityService;
import cn.com.allunion.sms.service.mybatis.UserbaseAuthorityService;
import cn.com.allunion.sms.service.mybatis.UserbaseService;
import cn.com.allunion.sms.service.mybatis.UserbaseSmsbusinessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@SuppressWarnings("serial")
public class UserBaseAction extends BaseAction {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseAction.class) ;
	/**
	 * 是否缓存
	 */
	public Boolean isCached = true;
	/**
	 * 页数大小
	 */
	private int pagesize;

    UserbaseService userbaseService ;

    UserbaseAuthorityService userbaseAuthorityService ;

    AuthorityService authorityService ;

    UserbaseSmsbusinessService userbaseSmsbusinessService ;

	/**
	 * 登陆验证
	 *
	 * @param userName
	 * @return 用户（基类）列表实例
	 */
	public Userbase findByUserName(String userName, String pwd) {
		List<Userbase> bas = userbaseService.findByCriteria(userName, null, true, null, null) ;
		if (bas != null && bas.size() != 0) {
			Userbase ub = bas.get(0);
			if (!pwd.equals(ub.getPassWord())) {
				return null;
			}
			if (userbaseAuthorityService.getCountByUserId(ub.getUserId()) > 0) {
				return ub;
			}

		}

		return null;
	}

	/**
	 * 根据页数取得页面内容
	 *
	 * @return 用户列表集合
	 */
	@Transactional
	public List<Userbase> getListByPage() {
		List<Userbase> list = userbaseService.getScrollData(1, pagesize).getResultList() ;
		return list;
	}

	/**
	 * 添加管理员
	 *
	 * @param username
	 * @param password
	 * @return 方法执行状态
	 */
	@Transactional(rollbackForClassName = "Exception")
	public String addNewManager(String username, String password) {
		Userbase user = new Userbase();
        user.setUserId(UUIDGenerator.generatorRandomUUID());
		user.setUserName(username);
		user.setPassWord(password);
		user.setUserType("admin");
		user.setWritepermission(true);
        boolean result = userbaseService.save(user) ;
		if (result) {
			UserbaseAuthority ubau = new UserbaseAuthority();
            ubau.setUserbaseAuthorityId(UUIDGenerator.generatorRandomUUID());
			ubau.setUserId(user.getUserId());
			ubau.setAuthorityId(authorityService.findByAuthorityString("ROLE_MANAGER").getAuthorityId());
            result = userbaseAuthorityService.save(ubau);
            return result ? "success" : "failure";
		}
		return "";
	}

	/**
	 * 修改管理员信息
	 *
	 * @param userId
	 * @param userName
	 * @param pwd
	 * @return 方法执行状态
	 */
	public String updateManager(String userId, String userName, String pwd) {
		Userbase userBase = userbaseService.findById(userId) ;
		userBase.setUserName(userName);
		userBase.setPassWord(pwd);
        boolean result = userbaseService.update(userBase) ;
		return result ? "success" : "failure";
	}

	/**
	 * 根据管理员名字查询管理员名称
	 *
	 * @param userName
	 * @param pwd
	 * @return 用户列表
	 */
	public List<Userbase> findbyUserBase(String userName, String pwd) {
		List<Userbase> ub = userbaseService.findByCriteria(userName, null, null, null, null) ;
		if (ub != null && ub.size() != 0) {
			Userbase usb = ub.get(0);
			if (!pwd.equals(usb.getPassWord())) {
				return null;
			}
			return ub;
		}
		return null;
	}

	/**
	 * 根据id删除一个用户
	 *
	 * @param id
	 * @return 方法执行结果
	 */
	public void delUserbase(String id) {
		userbaseService.deleteById(id) ;
	}

	/**
	 * 根据id冻结用户--当做删除用
	 *
	 * @param id
	 * @return 方法执行状态
	 */
	@Transactional(rollbackForClassName = "Exception")
	public String Dongjie(String id) {
		Userbase ub = userbaseService.findById(id) ;
		if (ub != null) {
			if (ub.getEnabled()) {
				ub.setEnabled(false);
			} else {
				ub.setEnabled(true);
			}
			return userbaseService.update(ub) ? "success" : "failure" ;
		}
		return "no user";
	}

	/**
	 * 分页查询查询所有管理员
	 *
	 * @return page
	 */
	public PageView<Userbase> findUBbypage(int pageCurrent) {

        QueryResult<Userbase> queryResult = userbaseService.getScrollData(pageCurrent, pagesize) ;
        PageView<Userbase> pageView = new PageView<Userbase>(pagesize, pageCurrent) ;
        pageView.setQueryResult(queryResult);
		return pageView;

	}

	/**
	 * 相对位置
	 *
	 * @param count 总条数
	 * @param pageSize 每页显示页数
	 * @return 相对位置
	 */
	public int lastPage(int count, int pageSize) {
		if (count % pageSize == 0) {
			return count / pageSize;
		}

		return count / pageSize + 1;
	}

	public int getPagesize() {
		return pagesize;
	}

	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}

	/**
	 * 为用户配置业务
	 *
	 * @param userId 用户ID
	 * @param list 业务列表
	 * @return 方法执行状态
	 */

	public String us_yw(String userId, ArrayList<Smsbusiness> list) {
		LOGGER.debug("这个配置业务传过来:" + list.size());
//		List<UserbaseSmsbusiness> lis = userbaseSmsbusinessService.findByUserId(id) ;
//		if (lis != null && lis.size() != 0) {
//			for (UserbaseSmsbusiness ubs : lis) {
//				hibernateDao.removeByEntity(ubs);
//			}
//		}
        userbaseSmsbusinessService.deleteByUserId(userId) ;

		if (list.size() != 0) {
			Userbase ub = userbaseService.findById(userId) ;

			if (ub != null) {
                UserbaseSmsbusiness ubsm ;
				for (Smsbusiness sm : list) {
                    LOGGER.debug("怎么会只有一个" + sm.getSmsBusinessName());
                    ubsm = new UserbaseSmsbusiness();
                    ubsm.setUserbaseSmsbusinessId(UUIDGenerator.generatorRandomUUID());
					ubsm.setUserId(ub.getUserId());
					ubsm.setSmsBusinessId(sm.getSmsBusinessID());

                    userbaseSmsbusinessService.save(ubsm) ;
				}
				return "success";
			}
		}
		return "no us or no sm";
	}

}
